<template>
  <view class="container">
    <view class="content">
      <view v-if="!imageUrl" style="position: relative; width: 100%; height: 100vh;">
        <camera v-if="cameraActive" device-position="back" flash="off" @error="error" style="width: 100%; height: 100%;"></camera>
        
        <view v-else class="camera-placeholder">
          <image src="/static/tujie/default_bg.jpg" style="width: 100%; height: 100%; object-fit: cover;"></image>
          <text class="placeholder-text" style="">点击按钮开启摄像头</text>
        </view>
        
        <view style="position: absolute; bottom: 20px; display: flex; width: 100%; flex-direction: column; align-items: center; justify-content: center; gap: 20px;">
          <div class="overlay-text">
            对准景物后拍照即可<text class="gradient-text">讲解</text>和<text class="gradient-text">动起来</text>
          </div>
          <div style="display: flex; gap: 20px; justify-content: center;">
            <div class="action-button-container" @click="toggleCamera">
              <div class="action-button" :class="{'active': cameraActive}">
                <div class="camera-toggle-icon" />
              </div>
              <text class="button-label">{{ cameraActive ? '关闭相机' : '开启相机' }}</text>
            </div>
            
            <div class="camera-button-container" @click="takePhoto">
              <div class="camera-button-outer" />
              <div class="camera-button">
                <div class="camera-icon" />
              </div>
            </div>
            
            <div class="action-button-container" @click="chooseImage">
              <div class="action-button">
                <div class="upload-icon" />
              </div>
              <text class="button-label">上传图片</text>
            </div>
          </div>
        </view>
      </view>

      <view v-else-if="showVideoPlayer" class="video-player-container">
        <text class="demo-title">演示效果</text>
        <view class="video-comparison">
          <image src="https://enjoy7-znt.oss-cn-shanghai.aliyuncs.com/20250416_f833d0a9556347b491acf84d945a4cd0.jpg" class="comparison-image" mode="aspectFill"></image>
          <video 
            src="https://enjoy7-znt.oss-cn-shanghai.aliyuncs.com/20250416_e155ab8057d346498362ff1e1a42da7f.mp4" 
            class="comparison-video"
            autoplay 
            loop
          ></video>
        </view>
        <view class="video-close-button" @click="closeVideo">
          <text class="video-close-icon">×</text>
        </view>
      </view>

      <view v-else class="result-view">
        <view class="back-button" @click="resetImage">
          <text class="back-icon">←</text>
        </view>

        <view class="landmark-recognized">
          <text class="landmark-text" v-if="recognizedLandmark">{{ recognizedLandmark.name }}</text>
          <text class="landmark-text" v-else>分析中...</text>
        </view>
        <view class="image-preview-wrapper" @click="playVideo">
          <view class="image-preview-container">
            <image :src="imageUrl" mode="aspectFill" class="preview-image" />
            
            <!-- Loading overlay -->
            <view v-if="isAnalyzing" class="loading-overlay">
              <view class="loading-spinner"></view>
              <text class="loading-text">{{ loadingText }}</text>
            </view>
          </view>
        </view>
        
        <view v-if="streamingResult" class="result-container">
          <text class="result-title">景点解析</text>
          <rich-text :nodes="renderMarkdown(streamingResult)" class="markdown-content"></rich-text>
        </view>
        
        <view v-if="error" class="error-container">
          <text class="error-message">{{ error }}</text>
        </view>

        <view v-if="suggestedQuestions" class="action-bubbles-container">
          <view v-for="(question, index) in suggestedQuestions.slice(0, 3)" :key="index" class="action-bubble" @click="handleQuestionClick(question)">
            <view class="bubble-circle">
              <text class="bubble-emoji">{{ question.icon || '❓' }}</text>
            </view>
            <text class="bubble-text">{{ question.text }}</text>
          </view>
          <!-- New bubble for refreshing questions -->
          <view class="action-bubble" @click="generateSuggestedQuestions(recognizedLandmark)" v-if="suggestedQuestions && suggestedQuestions[0] && suggestedQuestions[0].text !== '小莒正在思考中..'">
            <view class="bubble-circle">
              <text class="bubble-emoji">🔄</text>
            </view>
            <text class="bubble-text">换一批</text>
          </view>
        </view>
      </view>
    </view>
    
    <!-- Question Drawer -->
    <view class="drawer-overlay" :class="{'closing': isClosingDrawer}" v-if="showQuestionDrawer" @click="closeQuestionDrawer">
      <view class="drawer-container" @click.stop>
        <view class="drawer-header">
          <text class="drawer-title">{{ currentQuestion.text || '' }}</text>
          <view class="drawer-close" @click="closeQuestionDrawer">
            <text class="drawer-close-icon">×</text>
          </view>
        </view>
        <scroll-view id="drawerScrollView" class="drawer-content" scroll-y="true" :scroll-top="drawerScrollTop">
          <view v-if="isLoadingAnswer && !streamingAnswer" class="drawer-loading">
            <view class="loading-spinner"></view>
            <text class="loading-text">正在思考中...</text>
          </view>
          <view v-if="streamingAnswer" class="drawer-answer">
            <view v-if="isLoadingAnswer && !streamingAnswer.trim()" class="streaming-indicator">
              <view class="typing-dot"></view>
              <view class="typing-dot"></view>
              <view class="typing-dot"></view>
            </view>
            <rich-text :nodes="renderMarkdown(streamingAnswer)" class="markdown-content"></rich-text>
          </view>
        </scroll-view>
      </view>
    </view>
  </view>
</template>

<script>
import { defineComponent, ref, reactive } from 'vue';
import { marked } from 'marked';
import { highlightElement } from 'prismjs';

function error(e) {
  console.error('Camera error:', e);
  error.value = `相机错误: ${e.detail?.errMsg || '未知错误'}`;
  
  uni.showToast({
    title: '相机启动失败，请检查权限设置',
    icon: 'none',
    duration: 3000
  });
}

export default defineComponent({
  setup() {
    const imageUrl = ref('');
    const imageBase64 = ref('');
    const isAnalyzing = ref(false);
    const analysisResult = ref('');
    const error = ref('');
    const streamingResult = ref('');
    const recognizedLandmark = ref(null);
    const loadingText = ref('正在分析图片中...');
    const cameraActive = ref(false); // Camera starts off
    const showVideoPlayer = ref(false);
    const suggestedQuestions = ref([
      {
        "icon": "❓",
        "text": "小莒正在思考中.."
      },
      {
        "icon": "❓",
        "text": "小莒正在思考中.."
      },
      {
        "icon": "❓",
        "text": "小莒正在思考中.."
      }
    ]);
    const showQuestionDrawer = ref(false);
    const currentQuestion = ref({});
    const streamingAnswer = ref('');
    const isLoadingAnswer = ref(false);
    const isClosingDrawer = ref(false);
    let answerRequestTask = null; // Global request task
    const drawerScrollTop = ref(0);
    const generating = ref(true); // Add generating flag
    const requestId = ref(0); // Add a request ID to track the current request
    function initMarked() {
      marked.setOptions({
        renderer: new marked.Renderer(),
        pedantic: false,
        gfm: true,
        breaks: true,
        sanitize: false,
        smartLists: true,
        smartypants: false,
        xhtml: false
      });
    }

    function playVideo() {
      if (!isAnalyzing.value) {
        showVideoPlayer.value = true;
      }
    }
    
    function closeVideo() {
      showVideoPlayer.value = false;
    }
    function renderMarkdown(content) {
      try {
        if (!content) return '';
        return marked.parse(content);
      } catch (error) {
        console.error('Markdown渲染失败:', error);
        return content.replace(/\n/g, '<br>');
      }
    }
    function toggleCamera() {
      cameraActive.value = !cameraActive.value;
      
      if (cameraActive.value) {
        uni.showToast({
          title: '相机已开启',
          icon: 'none',
          duration: 1500
        });
      }
    }
    
    function takePhoto() {
      if (!cameraActive.value) {
        cameraActive.value = true;
        uni.showToast({
          title: '相机已开启，请对准景物后再次点击拍照',
          icon: 'none',
          duration: 2000
        });
        return;
      }
      
      const ctx = uni.createCameraContext();
      ctx.takePhoto({
        quality: 'high',
        success: (res) => {
          imageUrl.value = res.tempImagePath;
          uni.getFileSystemManager().readFile({
            filePath: res.tempImagePath,
            encoding: 'base64',
            success: (res) => {
              imageBase64.value = res.data;
              analyzeImage();
            },
            fail: (err) => {
              console.error('Failed to convert image to base64', err);
              error.value = '图片处理失败，请重试';
            }
          });
        },
        fail: (err) => {
          console.error('Failed to take photo', err);
          error.value = '拍照失败，请重试';
        }
      });
    }

    function chooseImage() {
      // downloadDefaultImage();
      // const tempFilePath = '/static/tujie/default_bg.jpg';
      // imageUrl.value = tempFilePath;
      // analysisResult.value = '';
      // error.value = '';
      // streamingResult.value = '';
      // recognizedLandmark.value = null;

      // analyzeImage();
      // uni.getFileSystemManager().readFile({
      //   filePath: imageUrl.value,
      //   encoding: 'base64',
      //   success: (res) => {
      //     imageBase64.value = res.data;
      //   },
      //   fail: (err) => {
      //     console.error('Failed to convert image to base64', err);
      //     error.value = '图片处理失败，请重试';
      //   }
      // });
      if (true) {
        uni.chooseImage({
          count: 1,
          sizeType: ['compressed'],
          sourceType: ['album'],
          success: (res) => {
            const tempFilePath = res.tempFilePaths[0];
            imageUrl.value = tempFilePath;
            analysisResult.value = '';
            error.value = '';
            streamingResult.value = '';
            recognizedLandmark.value = null;
            uni.getFileSystemManager().readFile({
              filePath: tempFilePath,
              encoding: 'base64',
              success: (res) => {
                imageBase64.value = res.data;
                analyzeImage();
              },
              fail: (err) => {
                console.error('Failed to convert image to base64', err);
                error.value = '图片处理失败，请重试';
              }
            });
          },
          fail: () => {
            uni.showToast({
              title: '已取消选择',
              icon: 'none'
            });
          }
        });
      }
    }

    function downloadDefaultImage() {
      const baseUrl = 'https://gugu-1251908093.cos.ap-guangzhou.myqcloud.com/default_bg.jpg';
      uni.showLoading({
        title: '加载默认图片中...'
      });
      
      uni.downloadFile({
        url: baseUrl,
        success: (res) => {
          if (res.statusCode === 200) {
            imageUrl.value = res.tempFilePath;
            console.log('下载的图片路径:', imageUrl.value);
            uni.hideLoading();
          } else {
            console.error('Failed to download image', res);
            error.value = '默认图片下载失败，请检查网络';
            uni.hideLoading();
          }
        },
        fail: (err) => {
          console.error('Download failed', err);
          error.value = '默认图片下载失败，请检查网络';
          uni.hideLoading();
        }
      });
    }

    function resetImage() {
      imageUrl.value = '';
      imageBase64.value = '';
      streamingResult.value = '';
      analysisResult.value = '';
      error.value = '';
      recognizedLandmark.value = null;
      showVideoPlayer.value = false;
      cameraActive.value = false;
    }
    function shareResults() {
      if (!streamingResult.value) {
        uni.showToast({
          title: '暂无分析结果可分享',
          icon: 'none'
        });
        return;
      }
      
      uni.showActionSheet({
        itemList: ['分享到微信', '保存到相册'],
        success: (res) => {
          if (res.tapIndex === 0) {
            uni.showToast({
              title: '分享功能开发中',
              icon: 'none'
            });
          } else if (res.tapIndex === 1) {
            uni.showToast({
              title: '保存功能开发中',
              icon: 'none'
            });
          }
        }
      });
    }

    function generateSuggestedQuestions(landmark) {
      console.log(landmark);
      if (!landmark) return;
      suggestedQuestions.value = [
        {
          "icon": "❓",
          "text": "小莒正在思考中.."
        },
        {
          "icon": "❓",
          "text": "小莒正在思考中.."
        },
        {
          "icon": "❓",
          "text": "小莒正在思考中.."
        }
      ];
      uni.request({
        url: `https://tushuoit.com/api/ju/vision_rag/scene-objects/suggest-questions/${landmark.name}`,
        success: (res) => {
            suggestedQuestions.value = res.data.questions;
            console.log(suggestedQuestions.value);
        }
      });
    }
    
    function handleQuestionClick(question) {
      console.log('Question clicked:', question);
      requestId.value++;
      const currentRequestId = requestId.value;
      if (answerRequestTask) {
        console.log('Aborting previous request task');
        // answerRequestTask.abort();
        // answerRequestTask = null;
      }
      currentQuestion.value = question;
      showQuestionDrawer.value = true;
      isLoadingAnswer.value = true;
      streamingAnswer.value = '';
      generating.value = true; // Reset generating flag to true
      const token = uni.getStorageSync('token') || '';
      const promptData = {
        prompt: `以下是关于${recognizedLandmark.value.name}的问题，请详细回答：
问题：${question.text}
${recognizedLandmark.value.description || ''}
请以专业、详细的方式回答这个问题，提供相关的历史背景和文化知识。`,
        apiKey: "juxianwenlv",
        stream: true
      };
      answerRequestTask = uni.request({
        url: 'https://tushuoit.com/api/ju/deepseek/chat',
        method: 'POST',
        header: {
          'Content-Type': 'application/json',
          'Authorization': token ? `Bearer ${token}` : ''
        },
        data: promptData,
        responseType: 'text',
        enableChunked: true,
        success: () => {},
        fail: (err) => {
          console.error('Streaming request failed', err);
          handleStreamingError();
        },
        complete: () => {
          if (currentRequestId === requestId.value) {
            isLoadingAnswer.value = false;
            console.log("Streaming request completed");
            if (!streamingAnswer.value.trim()) {
              streamingAnswer.value = '抱歉，未能获取回答内容。';
            }
            setTimeout(() => {
              if (currentRequestId === requestId.value) {
                isLoadingAnswer.value = false;
              }
            }, 500);
          }
        }
      });
      
      answerRequestTask.onChunkReceived((res) => {
        if (currentRequestId !== requestId.value || !generating.value) {
          console.log('Streaming cancelled, ignoring chunk');
          if (answerRequestTask) {
            // answerRequestTask.abort();
            // answerRequestTask = null;
          }
          return;
        }
        
        if (res && res.data) {
          try {
            const uint8Array = new Uint8Array(res.data);
            let text = String.fromCharCode.apply(null, uint8Array);
            text = decodeURIComponent(escape(text));
            
            console.log("Received chunk:", text.substring(0, 50) + "...");
            const lines = text.split('\n');
            for (const line of lines) {
              if (currentRequestId !== requestId.value || !generating.value) {
                console.log('Streaming cancelled during processing, stopping');
                return;
              }
              
              if (line.startsWith('data: ')) {
                if (line === 'data: [DONE]') {
                  console.log("Received DONE marker");
                  continue;
                }
                
                const jsonData = line.substring(6); // Remove "data: " prefix
                try {
                  const data = JSON.parse(jsonData);
                  console.log("Parsed JSON data:", data);
                  if (data.choices && data.choices[0]) {
                    if (data.choices[0].delta && data.choices[0].delta.content) {
                      if (currentRequestId === requestId.value && generating.value) {
                        const chunk = data.choices[0].delta.content;
                        streamingAnswer.value += chunk;
                        console.log("Added chunk to answer:", chunk);
                        if (streamingAnswer.value.length > 0 && isLoadingAnswer.value) {
                        }
                        scrollDrawerToBottom();
                      }
                    } 
                    else if (data.choices[0].message && data.choices[0].message.content) {
                      if (currentRequestId === requestId.value && generating.value) {
                        const chunk = data.choices[0].message.content;
                        streamingAnswer.value += chunk;
                        scrollDrawerToBottom();
                      }
                    }
                  }
                  else if (data.data && data.data.text) {
                    if (currentRequestId === requestId.value && generating.value) {
                      streamingAnswer.value += data.data.text;
                      scrollDrawerToBottom();
                    }
                  }
                } catch (e) {
                  console.error('解析JSON块失败', e, jsonData);
                }
              }
            }
          } catch (e) {
            console.error('处理数据块失败', e);
          }
        }
      });
    }
    function handleStreamingError() {
      isLoadingAnswer.value = false;
      streamingAnswer.value = '抱歉，无法获取回答内容，请稍后再试。';
    }
    function closeQuestionDrawer() {
      const drawerRef = ref(null);
      isClosingDrawer.value = true;
      generating.value = false;
      requestId.value++;
      if (answerRequestTask) {
        console.log('Cancelling streaming request on drawer close');
        // answerRequestTask.abort();
        // answerRequestTask = null;
      }
      setTimeout(() => {
        showQuestionDrawer.value = false;
        isClosingDrawer.value = false;
        streamingAnswer.value = ''; // Clear the answer when closing
      }, 300); // Match animation duration
    }
    function identifyLandmark(tempFilePath) {
      return new Promise((resolve, reject) => {
        loadingText.value = '识别中...';
        const token = uni.getStorageSync('token');
        
        uni.uploadFile({
          url: 'https://tushuoit.com/api/ju/vision_rag/scene-objects/match-image/?model_type=volcengine',
          filePath: tempFilePath,
          name: 'image_file',
          header: {
            'accept': 'application/json',
            'Authorization': token ? `Bearer ${token}` : ''
          },
          success: (res) => {
            try {
              if (res.statusCode === 200) {
                const data = JSON.parse(res.data);
                if (data && data.length > 0) {
                  recognizedLandmark.value = data[0];
                  generateSuggestedQuestions(data[0]);
                  resolve(data[0]);
                } else {
                  resolve(null);
                }
              } else {
                console.error('Landmark identification failed', res);
                resolve(null); // Continue with analysis anyway
              }
            } catch (err) {
              console.error('Failed to parse landmark data', err);
              resolve(null); // Continue with analysis anyway
            }
          },
          fail: (err) => {
            console.error('Landmark identification request failed', err);
            resolve(null); // Continue with analysis anyway
          }
        });
      });
    }
    async function analyzeImage() {
      // if (!imageBase64.value) {
      //   error.value = '请先选择图片';
      //   return;
      // }

      isAnalyzing.value = true;
      streamingResult.value = '';
      error.value = '';

      const token = uni.getStorageSync('token');
      if (!token) {
        isAnalyzing.value = false;
        uni.showModal({
          title: '提示',
          content: '请先登录后再使用此功能',
          success: (res) => {
            if (res.confirm) {
              uni.switchTab({
                url: '/pages/zhixun/index'
              });
            }
          }
        });
      }

      loadingText.value = '正在分析中...';
      const landmark = await identifyLandmark(imageUrl.value);
      
      if (landmark) {
        recognizedLandmark.value = landmark;
        isAnalyzing.value = false;
      }
    }
    initMarked();
    function scrollDrawerToBottom() {
      setTimeout(() => {
        try {
          const query = uni.createSelectorQuery();
          query.select('.drawer-answer')
            .fields({ size: true }, (answerData) => {
              if (!answerData) return;
              
              console.log('Answer content height:', answerData.height);
              drawerScrollTop.value = answerData.height + 1000; // Add extra to ensure it scrolls to bottom
              console.log('Setting scroll top to:', drawerScrollTop.value);
            })
            .exec();
        } catch (error) {
          console.error('Error in scrollDrawerToBottom:', error);
        }
      }, 50);
    }

    return {
      imageUrl,
      isAnalyzing,
      streamingResult,
      error,
      recognizedLandmark,
      loadingText,
      cameraActive,
      showVideoPlayer,
      toggleCamera,
      takePhoto,
      chooseImage,
      resetImage,
      shareResults,
      analyzeImage,
      renderMarkdown,
      playVideo,
      closeVideo,
      suggestedQuestions,
      handleQuestionClick,
      generateSuggestedQuestions,
      showQuestionDrawer,
      currentQuestion,
      streamingAnswer,
      isLoadingAnswer,
      closeQuestionDrawer,
      isClosingDrawer,
      scrollDrawerToBottom,
      drawerScrollTop,
      generating,
      requestId
    };
  }
});
</script>

<style>
.container {
  background-color: #f8f0e3;
  min-height: 100vh;
}

.header {
  text-align: center;
  margin-bottom: 30px;
}

.title {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 10px;
  color: #333;
  display: block;
}

.description {
  font-size: 14px;
  color: #666;
  display: block;
}

.content {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.image-container {
  width: 300px;
  height: 300px;
  border-radius: 12px;
  overflow: hidden;
  margin-bottom: 20px;
  background-color: #e0e0e0;
  position: relative;
}

.preview-image {
  width: 100%;
  height: 100%;
}

.upload-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.upload-icon {
  font-size: 48px;
  color: #999;
  margin-bottom: 10px;
}

.upload-text {
  font-size: 16px;
  color: #999;
}

.analyze-btn {
  width: 80%;
  height: 45px;
  background-color: #8b6b4a;
  color: white;
  border-radius: 22px;
  margin-bottom: 15px;
  font-size: 16px;
}

.reset-btn {
  width: 80%;
  height: 45px;
  background-color: #f0f0f0;
  color: #666;
  border-radius: 22px;
  margin-bottom: 15px;
  font-size: 16px;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 20px;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #8b6b4a;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 15px;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}

.loading-text {
  font-size: 16px;
  color: #666;
}
.landmark-recognized {
  margin: 5px auto;
  text-align: center;
}

.landmark-text {
  background: linear-gradient(135deg, #ff5b79 0%, #f57f17 50%, #a64ee6 100%);
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
  font-weight: bold;
  font-size: 40px;
}

.result-container {
  width: 100%;
  background-color: white;
  border-radius: 12px;
  padding: 20px;
  margin-top: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.result-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  margin-bottom: 15px;
  display: block;
}

.error-container {
  width: 100%;
  padding: 15px;
  background-color: #ffebee;
  border-radius: 8px;
  margin-top: 20px;
}

.error-message {
  color: #d32f2f;
  font-size: 14px;
}

/* Markdown styling */
.markdown-content {
  width: 100%;
  animation: fadeIn 0.3s ease-in-out;
}

.markdown-content h1,
.markdown-content h2,
.markdown-content h3,
.markdown-content h4,
.markdown-content h5,
.markdown-content h6 {
  margin-top: 16px;
  margin-bottom: 8px;
  font-weight: 600;
  line-height: 1.25;
}

.markdown-content h1 {
  font-size: 20px;
}

.markdown-content h2 {
  font-size: 18px;
}

.markdown-content h3 {
  font-size: 16px;
}

.markdown-content p {
  margin-bottom: 10px;
  line-height: 1.6;
  color: #333;
}

.markdown-content ul,
.markdown-content ol {
  margin-bottom: 10px;
  padding-left: 20px;
}

.markdown-content ul {
  list-style-type: disc;
}

.markdown-content ol {
  list-style-type: decimal;
}

.markdown-content li {
  margin-bottom: 5px;
}

.markdown-content code {
  background-color: #f1f1f1;
  padding: 2px 4px;
  border-radius: 3px;
  font-family: monospace;
}

.markdown-content pre {
  background-color: #f6f8fa;
  padding: 10px;
  border-radius: 5px;
  overflow-x: auto;
  margin-bottom: 10px;
}

.markdown-content blockquote {
  border-left: 3px solid #dfe2e5;
  padding-left: 10px;
  color: #6a737d;
  margin: 0 0 10px;
}

.markdown-content a {
  color: #8b6b4a;
  text-decoration: underline;
}

.markdown-content img {
  max-width: 100%;
  margin: 10px 0;
}

.markdown-content table {
  border-collapse: collapse;
  width: 100%;
  margin-bottom: 10px;
}

.markdown-content table th,
.markdown-content table td {
  border: 1px solid #ddd;
  padding: 8px;
}

.markdown-content table th {
  background-color: #f6f8fa;
  font-weight: bold;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

.overlay-text {
  background: rgba(0, 0, 0, 0.6);
  color: white;
  padding: 8px 18px;
  border-radius: 999px;
  font-size: 18px;
  white-space: nowrap;
  text-align: center;
  display: inline-flex;
  justify-content: center;
  align-items: center;
}

.gradient-text {
  font-weight: bold;
  background-image: linear-gradient(135deg, #ff5b79 0%, #a64ee6 100%);
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
  display: inline-block;
}

.action-button-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 5px;
}

.action-button {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background-color: white;
  border: 2px solid rgba(220, 220, 220, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.action-button.active {
  border-color: #ff5b79;
  box-shadow: 0 0 10px rgba(255, 91, 121, 0.5);
}

.button-label {
  color: white;
  font-size: 12px;
  text-align: center;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.5);
}

.camera-toggle-icon {
  width: 24px;
  height: 24px;
  background-image: linear-gradient(135deg, #ff5b79 0%, #a64ee6 100%);
  mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'%3E%3Cpath d='M12 8c-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4-1.79-4-4-4zm8.94 3A8.994 8.994 0 0 0 13 3.06V1h-2v2.06A8.994 8.994 0 0 0 3.06 11H1v2h2.06A8.994 8.994 0 0 0 11 20.94V23h2v-2.06A8.994 8.994 0 0 0 20.94 13H23v-2h-2.06zM12 19c-3.87 0-7-3.13-7-7s3.13-7 7-7 7 3.13 7 7-3.13 7-7 7z'/%3E%3C/svg%3E");
  mask-size: cover;
  -webkit-mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'%3E%3Cpath d='M12 8c-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4-1.79-4-4-4zm8.94 3A8.994 8.994 0 0 0 13 3.06V1h-2v2.06A8.994 8.994 0 0 0 3.06 11H1v2h2.06A8.994 8.994 0 0 0 11 20.94V23h2v-2.06A8.994 8.994 0 0 0 20.94 13H23v-2h-2.06zM12 19c-3.87 0-7-3.13-7-7s3.13-7 7-7 7 3.13 7 7-3.13 7-7 7z'/%3E%3C/svg%3E");
  -webkit-mask-size: cover;
}

.upload-icon {
  width: 24px;
  height: 24px;
  background-image: linear-gradient(135deg, #ff5b79 0%, #a64ee6 100%);
  mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 512 512'%3E%3Cpath d='M288 109.3V352c0 17.7-14.3 32-32 32s-32-14.3-32-32V109.3l-73.4 73.4c-12.5 12.5-32.8 12.5-45.3 0s-12.5-32.8 0-45.3l128-128c12.5-12.5 32.8-12.5 45.3 0l128 128c12.5 12.5 12.5 32.8 0 45.3s-32.8 12.5-45.3 0L288 109.3zM64 352H192c0 35.3 28.7 64 64 64s64-28.7 64-64H448c35.3 0 64 28.7 64 64v32c0 35.3-28.7 64-64 64H64c-35.3 0-64-28.7-64-64V416c0-35.3 28.7-64 64-64zM432 456a24 24 0 1 0 0-48 24 24 0 1 0 0 48z'/%3E%3C/svg%3E");
  mask-size: cover;
  -webkit-mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 512 512'%3E%3Cpath d='M288 109.3V352c0 17.7-14.3 32-32 32s-32-14.3-32-32V109.3l-73.4 73.4c-12.5 12.5-32.8 12.5-45.3 0s-12.5-32.8 0-45.3l128-128c12.5-12.5 32.8-12.5 45.3 0l128 128c12.5 12.5 12.5 32.8 0 45.3s-32.8 12.5-45.3 0L288 109.3zM64 352H192c0 35.3 28.7 64 64 64s64-28.7 64-64H448c35.3 0 64 28.7 64 64v32c0 35.3-28.7 64-64 64H64c-35.3 0-64-28.7-64-64V416c0-35.3 28.7-64 64-64zM432 456a24 24 0 1 0 0-48 24 24 0 1 0 0 48z'/%3E%3C/svg%3E");
  -webkit-mask-size: cover;
}

.camera-placeholder {
  width: 100%;
  height: 100%;
  background-color: #333;
  display: flex;
  justify-content: center;
  align-items: center;
}

.placeholder-text {
  color: white;
  font-size: 18px;
  text-align: center;
  padding: 20px;
  position: absolute; 
  top: 50%; 
  left: 50%; 
  transform: translate(-50%, -50%);
  text-shadow: 0 0 10px rgba(255, 255, 255, 0.7), 0 0 20px rgba(255, 255, 255, 0.5);
  animation: glow 1.5s ease-in-out infinite alternate;
}

@keyframes glow {
  from {
    text-shadow: 0 0 5px rgba(255, 255, 255, 0.7), 0 0 10px rgba(255, 255, 255, 0.5);
  }
  to {
    text-shadow: 0 0 10px rgba(255, 255, 255, 0.9), 0 0 20px rgba(255, 255, 255, 0.7), 0 0 30px rgba(255, 255, 255, 0.5);
  }
}

.camera-button-container {
  position: relative;
  width: 70px;
  height: 70px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.camera-button-outer {
  position: absolute;
  width: 70px;
  height: 70px;
  border-radius: 50%;
  border: 4px solid rgba(240, 240, 240, 0.9);
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.15);
}

.camera-button {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background-color: white;
  border: 2px solid rgba(220, 220, 220, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  z-index: 2;
}

.camera-icon {
  width: 30px;
  height: 30px;
  background-image: linear-gradient(135deg, #ff5b79 0%, #a64ee6 100%);
  mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 512 512'%3E%3Cpath d='M149.1 64.8L138.7 96H64C28.7 96 0 124.7 0 160V416c0 35.3 28.7 64 64 64H448c35.3 0 64-28.7 64-64V160c0-35.3-28.7-64-64-64H373.3L362.9 64.8C356.4 45.2 338.1 32 317.4 32H194.6c-20.7 0-39 13.2-45.5 32.8zM256 192a96 96 0 1 1 0 192 96 96 0 1 1 0-192z'/%3E%3C/svg%3E");
  mask-size: cover;
  -webkit-mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 512 512'%3E%3Cpath d='M149.1 64.8L138.7 96H64C28.7 96 0 124.7 0 160V416c0 35.3 28.7 64 64 64H448c35.3 0 64-28.7 64-64V160c0-35.3-28.7-64-64-64H373.3L362.9 64.8C356.4 45.2 338.1 32 317.4 32H194.6c-20.7 0-39 13.2-45.5 32.8zM256 192a96 96 0 1 1 0 192 96 96 0 1 1 0-192z'/%3E%3C/svg%3E");
  -webkit-mask-size: cover;
}

.camera-button:hover {
  transform: scale(1.05);
  box-shadow: 0 3px 8px rgba(0, 0, 0, 0.2);
}

/* Result view styles */
.result-view {
  display: flex;
  flex-direction: column;
  gap: 20px;
  width: 100%;
  height: 100vh;
}

/* Image preview wrapper for centering */
.image-preview-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
}

/* Modified image preview container to be circular */
.image-preview-container {
  width: 60%;
  aspect-ratio: 1/1;
  border-radius: 50%;
  overflow: hidden;
  position: relative;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  background-color: #f0f0f0;
  border: 4px solid white;
}

.preview-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* Modified loading overlay to be circular */
.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.7);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  border-radius: 50%;
}

.result-actions {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
  gap: 15px;
}

.action-btn {
  flex: 1;
  height: 45px;
  border-radius: 22px;
  font-size: 16px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.primary-btn {
  background-color: #8b6b4a;
  color: white;
}

.share-btn {
  background-image: linear-gradient(135deg, #ff5b79 0%, #a64ee6 100%);
  color: white;
}

.action-bubbles-container {
  position: absolute;
  width: 100%;
  height: 50vh;
  top: 50%;
  margin-top: 30px;
  padding: 0 10px;
}

.action-bubble {
  position: absolute;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  transition: transform 0.3s ease;
}

.action-bubble:nth-child(1) {
  animation: float1 3.5s ease-in-out infinite;
}

.action-bubble:nth-child(2) {
  animation: float2 4s ease-in-out infinite;
}

.action-bubble:nth-child(3) {
  animation: float3 3s ease-in-out infinite;
}

.action-bubble:nth-child(4) {
  animation: float3 10s ease-in-out infinite;
}

@keyframes float1 {
  0% {
    transform: translateY(0px);
  }
  50% {
    transform: translateY(-12px);
  }
  100% {
    transform: translateY(0px);
  }
}

@keyframes float2 {
  0% {
    transform: translateY(0px) translateX(0px);
  }
  50% {
    transform: translateY(-8px) translateX(5px);
  }
  100% {
    transform: translateY(0px) translateX(0px);
  }
}

@keyframes float3 {
  0% {
    transform: translateY(0px) rotate(0deg);
  }
  50% {
    transform: translateY(-10px) rotate(2deg);
  }
  100% {
    transform: translateY(0px) rotate(0deg);
  }
}

/* Position each bubble randomly */
.action-bubble:nth-child(1) {
  left: 5%;
  bottom: 80%;
}

.action-bubble:nth-child(2) {
  left: 20%;
  bottom: 10%;
}

.action-bubble:nth-child(3) {
  right: 5%;
  bottom: 40%;
}

.action-bubble:nth-child(4) {
  right: 40%;
  bottom: 60%;
}

.action-bubble:nth-child(4) .bubble-circle::before {
  background: linear-gradient(135deg, #3498db 0%, #2ecc71 100%);
}

        
.action-bubble:hover {
  transform: scale(1.1);
}

.action-bubble:nth-child(2):hover {
  transform: scale(1.1);
}

.bubble-circle {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  background-color: white;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  z-index: 1;
  overflow: hidden;
}

.bubble-circle::before {
  content: "";
  position: absolute;
  top: -2px;
  left: -2px;
  right: -2px;
  bottom: -2px;
  background: linear-gradient(135deg, #ff5b79 0%, #a64ee6 100%);
  border-radius: 50%;
  z-index: -1;
  animation: rotate 4s linear infinite;
}

.bubble-circle::after {
  content: "";
  position: absolute;
  top: 2px;
  left: 2px;
  right: 2px;
  bottom: 2px;
  background: white;
  border-radius: 50%;
  z-index: -1;
}

@keyframes rotate {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.bubble-emoji {
  font-size: 40px;
  z-index: 2;
}

.bubble-text {
  font-size: 16px;
  color: #333;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1), 0 0 5px rgba(255, 255, 255, 0.8), 0 0 10px rgba(255, 255, 255, 0.5);
  max-width: 130px;
  word-wrap: break-word;
  overflow-wrap: break-word;
  filter: drop-shadow(0 0 2px rgba(255, 255, 255, 0.7));
}

/* Video player styles */
.video-player-container {
  position: relative;
  width: 100%;
  height: 100vh;
  background-color: #000;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
}

.demo-title {
  color: white;
  font-size: 28px;
  font-weight: bold;
  margin: 20px 0;
  text-align: center;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}

.video-comparison {
  display: flex;
  flex-direction: row;
  gap: 10px;
  justify-content: center;
  align-items: center;
  width: 100%;
  padding: 0 3px;
  box-sizing: border-box;
  margin: 0 auto;
  height: 100vh;
}

.comparison-image,
.comparison-video {
  width: calc(50% - 10px);
  height: auto;
  aspect-ratio: 9/16;
  object-fit: contain;
  border-radius: 3px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
  background-color: #111;
}

.video-close-button {
  position: absolute;
  top: 20px;
  right: 20px;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 10;
  cursor: pointer;
  transition: all 0.2s ease;
}

.video-close-button:hover {
  background-color: rgba(0, 0, 0, 0.7);
  transform: scale(1.1);
}

.video-close-icon {
  color: white;
  font-size: 30px;
  font-weight: bold;
  line-height: 1;
}

/* Drawer styles */
.drawer-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 1000;
  display: flex;
  flex-direction: column;
  justify-content: flex-end;
  animation: fadeIn 0.3s ease;
}

.drawer-container {
  background-color: #fff;
  border-top-left-radius: 20px;
  border-top-right-radius: 20px;
  height: 75%;
  width: 100%;
  display: flex;
  flex-direction: column;
  box-shadow: 0 -4px 10px rgba(0, 0, 0, 0.1);
  animation: slideUp 0.3s ease;
}

.drawer-header {
  padding: 20px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.drawer-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  flex: 1;
}

.drawer-close {
  width: 30px;
  height: 30px;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 50%;
  background-color: #f5f5f5;
}

.drawer-close-icon {
  font-size: 20px;
  color: #666;
}

.drawer-content {
  flex: 1;
  padding-left: 20px;
  padding-right: 20px;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch; /* For better scrolling on iOS */
}

.drawer-loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  gap: 20px;
}

.drawer-answer {
  line-height: 1.6;
  color: #333;
  padding-bottom: 20px; /* Add padding at the bottom for better scrolling */
  width: 100%;
  word-wrap: break-word;
  overflow-wrap: break-word;
  max-width: 90%;
}

.drawer-answer .markdown-content {
  width: 100%;
  max-width: 100%;
  overflow-x: hidden;
}

.drawer-answer .markdown-content p,
.drawer-answer .markdown-content div,
.drawer-answer .markdown-content span {
  width: 100%;
  max-width: 100%;
  word-wrap: break-word;
  overflow-wrap: break-word;
  white-space: normal;
}

.drawer-answer img {
  max-width: 100%;
  height: auto;
}

.streaming-indicator {
  display: flex;
  justify-content: center;
  margin-top: 10px;
  margin-bottom: 10px;
}

.typing-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background-color: #a38d6d;
  margin: 0 3px;
  animation: typing 1.5s infinite ease-in-out;
}

.typing-dot:nth-child(2) {
  animation-delay: 0.2s;
}

.typing-dot:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes typing {
  0% { transform: translateY(0); }
  50% { transform: translateY(-5px); }
  100% { transform: translateY(0); }
}

@keyframes slideUp {
  from {
    transform: translateY(100%);
  }
  to {
    transform: translateY(0);
  }
}

@keyframes slideDown {
  from {
    transform: translateY(0);
  }
  to {
    transform: translateY(100%);
  }
}

.drawer-overlay.closing {
  animation: fadeOut 0.3s ease forwards;
}

.drawer-overlay.closing .drawer-container {
  animation: slideDown 0.3s ease forwards;
}

@keyframes fadeOut {
  from {
    opacity: 1;
  }
  to {
    opacity: 0;
  }
}

/* Add styles for preset questions */
.input-preset {
  height: var(--ai-chat-input-preset-height, 40px);
  padding: 0 3.2vw;
  display: flex;
  align-items: center;
  gap: 2.133vw;
  overflow: auto;
  margin-bottom: 10px;
  background-color: transparent;
}

.preset-scroll {
  width: 100%;
  white-space: nowrap;
}

.preset {
  display: flex;
  align-items: center;
  gap: 2.133vw;
  padding-right: 3.2vw;
}

.preset-item {
  flex: none;
  padding: 1.333vw 3.2vw;
  border-radius: 5.333vw 0 5.333vw 5.333vw;
  background-color: var(--ai-primary-color, rgba(139, 107, 74, 0.1));
  color: #fff;
  font-family: PingFang SC;
  font-size: 3.467vw;
  font-weight: 400;
  line-height: 4.8vw;
  white-space: nowrap;
  cursor: pointer;
  transition: all 0.3s ease;
  color: #8b6b4a;
}

.preset-item:active {
  opacity: 0.8;
}

.back-button {
  position: absolute;
  top: 10px;
  left: 20px;
  width: 40px;
  height: 40px;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: rgba(255, 255, 255, 0.8);
  border-radius: 50%;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.2s ease;
}

.back-button:active {
  transform: scale(0.95);
  background-color: rgba(255, 255, 255, 0.9);
}

.back-icon {
  color: #8b6b4a;
  font-size: 22px;
  font-weight: normal;
}
</style>
